package org.example.servlet;

import org.example.DAO.UserDao;
import org.example.entity.User;
import org.example.impl.UserDaoImpl;
import org.example.Util.DataSourceUtil;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.sql.SQLException;

@WebServlet("/userChangePassword")
public class UserChangePasswordServlet extends HttpServlet {
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        HttpSession session = request.getSession(false);
        if (session == null || session.getAttribute("user") == null) {
            response.sendRedirect("Userlogin.jsp");
            return;
        }

        // 获取User对象而不是String
        User user = (User) session.getAttribute("user");
        String username = user.getUsername(); // 从User对象获取用户名
        String oldPassword = request.getParameter("oldPassword");
        String newPassword = request.getParameter("newPassword");

        // 验证输入
        if (oldPassword == null || oldPassword.trim().isEmpty() ||
                newPassword == null || newPassword.trim().isEmpty()) {
            request.setAttribute("error", "原密码和新密码不能为空");
            request.getRequestDispatcher("personal-management.jsp").forward(request, response);
            return;
        }

        UserDao userDao = new UserDaoImpl(DataSourceUtil.getDataSource());

        try {
            if (userDao.changePassword(username, oldPassword, newPassword)) {
                request.setAttribute("message", "密码修改成功，请使用新密码重新登录");
                // 密码修改成功后使会话失效
                session.invalidate();
                response.sendRedirect("Userlogin.jsp");
                return;
            } else {
                request.setAttribute("error", "原密码错误，密码修改失败");
            }
        } catch (SQLException e) {
            System.err.println("修改密码时数据库异常: " + e.getMessage());
            e.printStackTrace();
            request.setAttribute("error", "系统错误: 数据库访问异常，请稍后再试");
        }

        request.getRequestDispatcher("personal-management.jsp").forward(request, response);
    }
}